package com.xxx.landlord.client.controller;

import javafx.animation.Animation;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import static javafx.application.Application.launch;

public class WaitController {
    @FXML Label wait_lbl_p1;//名字_玩家1
    @FXML Label wait_lbl_p2;//名字_玩家2
    @FXML Label wait_lbl_p3;//名字_玩家3
    @FXML Label wait_lbl_info;//消息框
    @FXML ImageView img_p1;//图片_人物1
    @FXML ImageView img_p2;//图片_人物2
    @FXML ImageView img_p3;//图片_人物3
    @FXML ImageView img_ready1;//就绪按钮1
    @FXML ImageView img_ready2;//就绪按钮2
    @FXML ImageView img_ready3;//就绪按钮3
    @FXML Canvas canvas;//画布
    GraphicsContext gc;//画布上下文
    Scene scene;//场景
    BufferedReader in;//网络读
    PrintWriter out;//网络写
    int order;//记录身份【1，2，3】
    boolean myReady = false; //本人是否就绪，默认否
    int Game_Status = 0;//游戏是否开始，默认否【0未开始 1开始前读秒 2正在进行 3结算】

    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(WaitController.class.getResource("hello-view.fxml"));
        //先加载fxml，确保注入完成
        Parent root = fxmlLoader.load();
        scene = new Scene(root, 500, 580);
        stage.setTitle("waiting...");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
        //当窗口被关闭时，强制退出程序
        stage.setOnCloseRequest(event -> {
            System.exit(0);
        });

        // 初始化画布上下文
//        if (canvas != null) {
//            gc = canvas.getGraphicsContext2D();
//            inputGame();
//            AnimationTimer timer = new AnimationTimer() {
//                @Override
//                public void handle(long now) {
//                    gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
//                    updateGame();
//                    renderGame();
//                }
//            };
//            timer.start();
//        }else{
//            System.out.println("canvas is null");
//        }

    }

    @FXML
    public void initialize() throws IOException {
        wait_lbl_p1.setText("1");
        wait_lbl_p2.setText("2");
        wait_lbl_p3.setText("3");
        // 网络连接
        Platform.runLater(() -> {
            try{
                netProcess();
            }catch(Exception e){
                e.printStackTrace();
            }
        });
    }

    void inputGame() {
        //处理游戏输入
//        canvas.setOnMouseClicked(event -> {
//            System.out.println("点击了"+event.getX());
//        });
    }

    void updateGame() {
        //更新
    }

    void renderGame() {
        //渲染
    }
    //网络处理
    void netProcess() throws IOException {
        Socket socket;
        try{
            socket = new Socket("localhost", 8080);
        }catch (Exception e){
            wait_lbl_info.setText("Fail to connect to server");
            return;
        }
        wait_lbl_info.setText("Success!Waiting for other players...");
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读
        out = new PrintWriter(socket.getOutputStream(), true);//写
        //创建消息读取的循环线程
        new Thread(() -> {
            try{
                RUN();
            }catch(IOException e){
                e.printStackTrace();
            }
        }).start();
    }

    Image readyImage = new Image(getClass().getResource("/com/edu/example/test/img/wait_ready.png").toExternalForm());
    Image unreadyImage = new Image(getClass().getResource("/com/edu/example/test/img/wait_unready.png").toExternalForm());

    void RUN() throws IOException {
        String inputLine;
        while((inputLine = in.readLine()) != null){
            if(inputLine.equals("U1")) {
                order = 1;
                Platform.runLater(() -> this.wait_lbl_p1.setText("你"));
            }else if(inputLine.equals("U2")) {
                order = 2;
                Platform.runLater(() -> this.wait_lbl_p2.setText("你"));
            }else if(inputLine.equals("U3")) {
                order = 3;
                Platform.runLater(() -> this.wait_lbl_p3.setText("你"));
            }
            //接收到就绪状态发生改变的消息
            if(inputLine.equals("U1!Ready")){
                Platform.runLater(() -> this.img_ready1.setImage(readyImage));
            }else if(inputLine.equals("U1!Unready")){
                Platform.runLater(() -> this.img_ready1.setImage(unreadyImage));
            }else if(inputLine.equals("U2!Ready")){
                Platform.runLater(() -> this.img_ready2.setImage(readyImage));
            }else if(inputLine.equals("U2!Unready")){
                Platform.runLater(() -> this.img_ready2.setImage(unreadyImage));
            }else if(inputLine.equals("U3!Ready")){
                Platform.runLater(() -> this.img_ready3.setImage(readyImage));
            }else if(inputLine.equals("U3!Unready")){
                Platform.runLater(() -> this.img_ready3.setImage(unreadyImage));
            }
            //倒数读秒
            if(!inputLine.equals("START0")&&inputLine.startsWith("START")){
                Game_Status = 1;//立即改变游戏状态
                Platform.runLater(() -> this.wait_lbl_info.setText("Game begin!"));
            }

        }
    }

    //点击就绪按钮事件
    @FXML
    void onReady1(){
        System.out.println("Ready1 is called");
        onReady(img_ready1,1);
    }
    @FXML
    void onReady2(){
        System.out.println("Ready2 is called");
        onReady(img_ready2,2);
    }
    @FXML
    void onReady3(){
        System.out.println("Ready3 is called");
        onReady(img_ready3,3);
    }

    //就绪按钮点击事件
    void onReady(ImageView img_ready, int index){
        //只允许点击自己的就绪按钮
        if(index!=order)return;
        //只允许在游戏还没开始的时候操作就绪按钮
        if(Game_Status!=0)return;
        System.out.println("Before toggle,myReady="+myReady);
        //修改本人的就绪状态
        myReady = !myReady;
        System.out.println("After toggle,myReady="+myReady);
        if(myReady){
            img_ready.setImage(readyImage);
            out.println("U"+order+"!Ready");//把本人就绪现况发给服务端
        }else{
            img_ready.setImage(unreadyImage);
            out.println("U"+order+"!Unready");//把本人未就绪现况发给服务端
        }
    }
    public static void main(String[] args) {
        launch();
    }
}
